import '../../../public.dart';

class PinInputDialog {
  static Future<void> show({
    required BuildContext context,
    required Function(String pin) onConfirm,
  }) async {
    // 4个独立的输入框控制器
    final List<TextEditingController> controllers = List.generate(
      4,
      (index) => TextEditingController(),
    );

    // 4个焦点节点
    final List<FocusNode> focusNodes = List.generate(4, (index) => FocusNode());

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _PinInputBottomSheet(
        controllers: controllers,
        focusNodes: focusNodes,
        onConfirm: (pin) async {
          Navigator.of(context).pop();
          await onConfirm(pin);
        },
        onCancel: () => Navigator.of(context).pop(),
      ),
    );
  }
}

class _PinInputBottomSheet extends StatefulWidget {
  final List<TextEditingController> controllers;
  final List<FocusNode> focusNodes;
  final Function(String) onConfirm;
  final VoidCallback onCancel;

  const _PinInputBottomSheet({
    required this.controllers,
    required this.focusNodes,
    required this.onConfirm,
    required this.onCancel,
  });

  @override
  State<_PinInputBottomSheet> createState() => _PinInputBottomSheetState();
}

class _PinInputBottomSheetState extends State<_PinInputBottomSheet> {
  String _currentPin = '';

  @override
  void initState() {
    super.initState();
    // 自动聚焦到第一个输入框
    Future.delayed(const Duration(milliseconds: 100), () {
      if (mounted) {
        widget.focusNodes[0].requestFocus();
      }
    });
  }

  @override
  void dispose() {
    // 清理资源以避免内存泄漏
    for (final controller in widget.controllers) {
      controller.dispose();
    }
    for (final focusNode in widget.focusNodes) {
      focusNode.dispose();
    }
    super.dispose();
  }

  String get pin {
    return widget.controllers.map((controller) => controller.text).join();
  }

  bool get isValid => pin.length == 4;

  void _onPinChanged(String value, int index) {
    setState(() {
      _currentPin = pin;
    });

    if (value.isNotEmpty && index < 3) {
      // 自动跳转到下一个输入框
      widget.focusNodes[index + 1].requestFocus();
    } else if (value.isEmpty && index > 0) {
      // 删除时跳转到上一个输入框
      widget.focusNodes[index - 1].requestFocus();
    }
  }

  void _onSubmitted(int index) {
    if (index == 3 && pin.length == 4) {
      // 最后一位输入完成后，自动确认
      widget.onConfirm(pin);
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Container(
      width: ScreenUtil.width,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24),
          topRight: Radius.circular(24),
        ),
      ),
      child: Padding(
        padding: EdgeInsets.only(
          bottom: MediaQuery.of(context).viewInsets.bottom,
          left: 24,
          right: 24,
          top: 24,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 顶部拖拽条
            Container(
              width: 32,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(height: 24),

            // 标题
            Text(
              'Enter PIN',
              style: theme.textTheme.headlineSmall?.copyWith(
                fontWeight: FontWeight.w600,
                color: Colors.grey[800],
              ),
            ),
            const SizedBox(height: 8),

            // 副标题
            Text(
              'Please enter your 4-digit PIN to confirm withdrawal',
              style: theme.textTheme.bodyMedium?.copyWith(
                color: Colors.grey[600],
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 32),

            // 4个PIN输入框
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: List.generate(4, (index) {
                return _buildPinInputBox(
                  controller: widget.controllers[index],
                  focusNode: widget.focusNodes[index],
                  index: index,
                );
              }),
            ),

            // PIN状态显示
            if (_currentPin.isNotEmpty)
              Padding(
                padding: const EdgeInsets.only(top: 20),
                child: Text(
                  'PIN: ${'*' * _currentPin.length}',
                  style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                ),
              ),

            const SizedBox(height: 32),

            // 按钮组
            Row(
              children: [
                // 取消按钮
                Expanded(
                  child: OutlinedButton(
                    onPressed: widget.onCancel,
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      side: BorderSide(color: Colors.grey[300]!),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: Text(
                      'Cancel',
                      style: TextStyle(
                        color: Colors.grey[600],
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 16),

                // 确认按钮
                Expanded(
                  child: ElevatedButton(
                    onPressed: isValid ? () => widget.onConfirm(pin) : null,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF1DE9B6),
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      elevation: isValid ? 2 : 0,
                      shadowColor: isValid
                          ? const Color(0xFF1DE9B6)
                          : Colors.transparent,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: Text(
                      'Confirm',
                      style: TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 16,
                        color: isValid
                            ? Colors.white
                            : Colors.white.withOpacity(0.5),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
          ],
        ),
      ),
    );
  }

  Widget _buildPinInputBox({
    required TextEditingController controller,
    required FocusNode focusNode,
    required int index,
  }) {
    return Container(
      width: 60,
      height: 60,
      decoration: BoxDecoration(
        border: Border.all(
          color: controller.text.isNotEmpty
              ? const Color(0xFF1DE9B6)
              : Colors.grey[300]!,
          width: 2,
        ),
        borderRadius: BorderRadius.circular(12),
      ),
      child: TextField(
        controller: controller,
        focusNode: focusNode,
        keyboardType: TextInputType.number,
        obscureText: true,
        maxLength: 1,
        textAlign: TextAlign.center,
        style: const TextStyle(
          fontSize: 24,
          fontWeight: FontWeight.w600,
          color: Colors.black87,
          letterSpacing: 2,
        ),
        decoration: const InputDecoration(
          border: InputBorder.none,
          counterText: '',
        ),
        onChanged: (value) {
          _onPinChanged(value, index);
        },
        onSubmitted: (value) {
          _onSubmitted(index);
        },
      ),
    );
  }
}
